package com.daigg.hoteladmin.ex.handler;


import com.daigg.hoteladmin.ex.ServiceException;
import com.daigg.hoteladmin.tools.JsonResult;
import com.daigg.hoteladmin.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler  {

    public GlobalExceptionHandler() {
        log.debug("创建全局异常处理器对象：GlobalExceptionHandler");
    }

    @ExceptionHandler
    public String handleServiceException(ServiceException e) {
        log.debug("处理请求的方法抛出了ServiceException，将统一处理");
        return e.getMessage();
    }


    @ExceptionHandler
    public JsonResult<Void> handleBindException(BindException e) {
        log.debug("开始处理BindException");
        String defaultMessage = e.getFieldError().getDefaultMessage();
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST, defaultMessage);
    }

    @ExceptionHandler
    @ResponseBody
    public JsonResult MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e)
    {

        //捕获数据校验异常
        JsonResult resultInfo = new JsonResult();
        resultInfo.setState(600);
        //获取实体类定义的校验注解字段上的message作为异常信息，@NotBlank(message = "用户密码不能为空！")异常信息即为"用户密码不能为空！"
        resultInfo.setMessage(e.getBindingResult().getFieldError().getDefaultMessage());
        return resultInfo;
    }

}
